package com.gzhryc.shared_device.cdcz.api;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.iot.core.IOTNodeEntity;
import com.gzhryc.shared_device.cdcz.api.protocol.*;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.cdcz.core.models.CDCZChargeCommand;
import com.gzhryc.shared_device.cdcz.core.models.CDCZExecuteResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * 充电插座HttpAPI网络服务
 * @version 2022-10-03
 */
public class CDCZHttpAPINetworkService implements ICDCZNetworkService {

    private static Logger log = Logger.getLogger(CDCZHttpAPINetworkService.class);


    private IOTNodeEntity iotNode;
    private CloseableHttpClient httpClient;

    public CDCZHttpAPINetworkService(IOTNodeEntity iotNode) {
        this.iotNode = iotNode;
        this.httpClient = HttpClients.createDefault();
    }

    @Override
    public CDCZExecuteResult charge(CDCZChargeCommand chargeCommand) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdcz/charge.do").build();

            CDCZHttpChargeRequest apiReq = new CDCZHttpChargeRequest();
            apiReq.setBody(ClassTools.copy(apiReq.getBody(),chargeCommand));

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("充电插座开启充电返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDCZHttpChargeResponse apiResp = JsonTools.fromJson(str, CDCZHttpChargeResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("充电插座开启充电错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult closeCharge(String deviceSn, Integer slotNum) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/"+iotNode.getId()+"/api/v1/cdcz/charge/close.do").build();

            CDCZHttpChargeCloseRequest apiReq = new CDCZHttpChargeCloseRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setSlotNum(slotNum);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("充电插座开启充电返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CDCZHttpChargeResponse apiResp = JsonTools.fromJson(str, CDCZHttpChargeResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch(Exception e){
            log.error("充电插座开启充电错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult searchDevice(String deviceSn) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/search.do").build();

            CDCZHttpSearchRequest apiReq = new CDCZHttpSearchRequest();
            apiReq.getBody().setDeviceSn(deviceSn);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("充电插座信息查询返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpSearchResponse apiResp = JsonTools.fromJson(str, CDCZHttpSearchResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座信息查询错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult restart(String deviceSn) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/restart.do").build();

            CDCZHttpRestartRequest apiReq = new CDCZHttpRestartRequest();
            apiReq.getBody().setDeviceSn(deviceSn);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("充电插座主机重启返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpRestartResponse apiResp = JsonTools.fromJson(str, CDCZHttpRestartResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座主机重启错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult findSlaveDevice(String mainDevice, Integer bindIndex) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/slave_device/find.do").build();

            CDCZHttpFindSlaveDeviceRequest apiReq = new CDCZHttpFindSlaveDeviceRequest();
            apiReq.getBody().setMainDeviceSn(mainDevice);
            apiReq.getBody().setBindIndex(bindIndex);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("查询充电插座从机返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpFindSlaveDeviceResponse apiResp = JsonTools.fromJson(str, CDCZHttpFindSlaveDeviceResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座查询从机错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult bindSlaveDevice(String mainDevice, Integer bindIndex, String deviceSn) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/slave_device/bind.do").build();

            CDCZHttpBindSlaveDeviceRequest apiReq = new CDCZHttpBindSlaveDeviceRequest();
            apiReq.getBody().setMainDeviceSn(mainDevice);
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setBindIndex(bindIndex);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("绑定充电插座从机返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpBindSlaveDeviceResponse apiResp = JsonTools.fromJson(str, CDCZHttpBindSlaveDeviceResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座绑定从机错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult removeSlaveDevice(String mainDevice) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/slave_device/remove.do").build();

            CDCZHttpRemoveSlaveDeviceRequest apiReq = new CDCZHttpRemoveSlaveDeviceRequest();
            apiReq.getBody().setMainDeviceSn(mainDevice);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("移除充电插座从机返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpRemoveSlaveDeviceResponse apiResp = JsonTools.fromJson(str, CDCZHttpRemoveSlaveDeviceResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座移除从机错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public CDCZExecuteResult changeMQTTConnect(String deviceSn,String type,String ip,String port,String userName,String userPwd) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/mqtt_connect/change.do").build();

            CDCZHttpChangeMQTTConnectRequest apiReq = new CDCZHttpChangeMQTTConnectRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setType(type);
            apiReq.getBody().setIp(ip);
            apiReq.getBody().setPort(port);
            apiReq.getBody().setUserName(userName);
            apiReq.getBody().setUserPwd(userPwd);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("切换充电插座MQTT连接返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpChangeMQTTConnectResponse apiResp = JsonTools.fromJson(str, CDCZHttpChangeMQTTConnectResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("切换充电插座MQTT连接错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult upgradeDownload(String deviceSn, String packagePath, String packageCRC) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/upgrade.do").build();

            CDCZHttpUpgradeRequest apiReq = new CDCZHttpUpgradeRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setType(2);
            apiReq.getBody().setPackagePath(packagePath);
            apiReq.getBody().setPackageCRC(packageCRC);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("充电插座主机升级固件下载返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpUpgradeResponse apiResp = JsonTools.fromJson(str, CDCZHttpUpgradeResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座主机重启错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public CDCZExecuteResult upgrade(String deviceSn, String packagePath, String packageCRC) {
        CDCZExecuteResult result = new CDCZExecuteResult(CDCZExecuteResult.FAIL);
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(iotNode.getApiUrl() + "/iot/" + iotNode.getId() + "/api/v1/cdcz/upgrade.do").build();

            CDCZHttpUpgradeRequest apiReq = new CDCZHttpUpgradeRequest();
            apiReq.getBody().setDeviceSn(deviceSn);
            apiReq.getBody().setType(1);
            apiReq.getBody().setPackagePath(packagePath);
            apiReq.getBody().setPackageCRC(packageCRC);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("authorization",iotNode.getApiToken());
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("充电插座主机升级固件返回：" + str);
                if (StringUtils.isNotBlank(str)) {
                    CDCZHttpUpgradeResponse apiResp = JsonTools.fromJson(str, CDCZHttpUpgradeResponse.class);
                    if(apiResp != null) {
                        if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            result.setCode(apiResp.getBody().getResultCode());
                            result.setMsg(apiResp.getBody().getErrorMsg());
                            result.setMessageId(apiResp.getBody().getMessageId());
                        }else{
                            result.setMsg(apiResp.getMsg());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("充电插座主机重启错误，" + e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


}
